﻿/*
COPYRIGHT (C) 2010 EPISERVER AB

THIS FILE IS PART OF PROPERTY PACK FOR EPISERVER CMS.
DYNAMIC CONTENT CONTRIB FOR EPISERVER CMS IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

PROPERTY PACK FOR EPISERVER CMS IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER GENERAL PUBLIC LICENSE FOR MORE DETAILS.
YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH PROPERTY PACK FOR EPISERVER CMS. IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EPiServer.Web.PropertyControls;
using EPiServer.Core.PropertySettings;
using EPiServer.Core;
using EPiServer.Web.WebControls;
using System.Web.UI;
using EPiServer.DataAbstraction;
using System.Web.UI.WebControls;
using EPiServer.UI.WebControls;

namespace EPiServer.Research.Properties.PropertyList
{
    [PropertySettings(typeof(PropertyListSettings), true)]
    public class PropertyListControl : PropertyStringControl, INamingContainer
    {
        protected Table propertyPanel;

        protected ToolButton addNewBtn;

        protected int PropertyCount
        {
            get
            {
                if (ViewState["PropertyCount"] == null) ViewState.Add("PropertyCount", 0);
                return (int)ViewState["PropertyCount"];
            }
            set
            {
                ViewState["PropertyCount"] = value;
            }
        }

        public override void CreateEditControls()
        {
            Controls.Add(new LiteralControl("<br/>"));
            propertyPanel = new Table();
            Controls.Add(propertyPanel);
            UpdateExistingProperties();

            addNewBtn = new ToolButton();
            addNewBtn.ID = "addBtn";
            addNewBtn.Text = "Add";
            addNewBtn.DisablePageLeaveCheck = true;
            addNewBtn.Click += new EventHandler(addNewBtn_Click);
            Controls.Add(addNewBtn);



        }

        private void UpdateExistingProperties()
        {
            if (!Page.IsPostBack)
            {
                //Load existing properties
                
                var lst=(PropertyData as PropertyList).PropertyCollection;
                PropertyCount = lst.Count;
                for (int i = 0; i < lst.Count; i++)
                {
                    InsertProperty(i, lst[i]);
                }
                
            }
            else
            {
                for (int i = 0; i < PropertyCount; i++)
                {
                    InsertProperty(i, CreateNewPropertyData());
                }
            }
        }

        private void InsertProperty(int id, PropertyData property)
        {
            TableRow pp = new TableRow();
            pp.Style.Add(HtmlTextWriterStyle.Margin, "2px");

            var prop = new Property(property);
            prop.ID = "prop" + id.ToString();
            prop.EditMode = true;

            TableCell tcBtnUp = new TableCell();
            ImageButton upBtn = new ImageButton();
            upBtn.ID = "up" + id.ToString();
            upBtn.CommandName = "Up";
            upBtn.CommandArgument = id.ToString();
            upBtn.ImageUrl = EPiServer.Web.PageExtensions.ThemeUtility.GetImageThemeUrl(Page, "Tools/Up.gif");
            upBtn.Command += new CommandEventHandler(upBtn_Command);
            upBtn.Visible = (id > 0);

            TableCell tcBtnDown = new TableCell();
            ImageButton downBtn = new ImageButton();
            downBtn.ID = "down" + id.ToString();
            downBtn.CommandName = "Down";
            downBtn.CommandArgument = id.ToString();
            downBtn.ImageUrl = EPiServer.Web.PageExtensions.ThemeUtility.GetImageThemeUrl(Page, "Tools/Down.gif");
            downBtn.Command += new CommandEventHandler(upBtn_Command);
            downBtn.Visible = (id < (PropertyCount-1));


            tcBtnUp.Controls.Add(upBtn);
            tcBtnDown.Controls.Add(downBtn);
            pp.Controls.Add(tcBtnUp);
            pp.Controls.Add(tcBtnDown);
            TableCell tcProp = new TableCell();
            tcProp.Controls.Add(prop);
            pp.Controls.Add(tcProp);


            propertyPanel.Controls.Add(pp);
            
        }

        void upBtn_Command(object sender, CommandEventArgs e)
        {
            EnsureChildControls();
            if (e.CommandName == "Up")
            {
                var p1 = propertyPanel.FindControl("prop" + e.CommandArgument) as Property;
                var p2 = propertyPanel.FindControl("prop" + ((int.Parse((string)e.CommandArgument)) - 1).ToString()) as Property;
                SetValuesForPropertyControls(p1);
                SetValuesForPropertyControls(p2);
                var p = p1.InnerProperty;
                p1.InnerProperty = p2.InnerProperty;
                p2.InnerProperty = p;
                
            }
            else if (e.CommandName == "Down")
            {
                var p1 = propertyPanel.FindControl("prop" + e.CommandArgument) as Property;
                var p2 = propertyPanel.FindControl("prop" + ((int.Parse((string)e.CommandArgument)) + 1).ToString()) as Property;
                SetValuesForPropertyControls(p1);
                SetValuesForPropertyControls(p2);
                var p = p1.InnerProperty;
                p1.InnerProperty = p2.InnerProperty;
                p2.InnerProperty = p;
            }
            else if (e.CommandName == "Delete")
            {
            }

        }


        public override void ApplyChanges()
        {
            SetValuesForPropertyControls(propertyPanel);
            var lst = new List<PropertyData>();
            for (int i = 0; i < PropertyCount; i++)
            {
                lst.Add((propertyPanel.FindControl("prop" + i.ToString()) as Property).InnerProperty);
            }
            (PropertyData as PropertyList).PropertyCollection = lst;// propertyPanel.Controls.Cast<Control>().Where(c => c is Property).Cast<Property>().Select(p => p.InnerProperty).ToList();
        }



        private PropertyData CreateNewPropertyData()
        {
            return (PropertyData as PropertyList).CreateNewPropertyData();
        }





        public virtual void SetValuesForPropertyControls(Control control)
        {
            foreach (Control control2 in control.Controls)
            {
                if ((control2 is IPropertyControl) && ((IPropertyControl)control2).Enabled)
                {
                    ((IPropertyControl)control2).ApplyChanges();
                }
                this.SetValuesForPropertyControls(control2);
            }
        }


        //Only every other click event is fired!

        void addNewBtn_Click(object sender, EventArgs e)
        {
            InsertProperty(PropertyCount, CreateNewPropertyData());
            PropertyCount++;            
        }
    }
}
